const net = require('net');
const mysql = require("mysql");
const dbOption = require("../db/config");

class NetSocketServer {
  constructor() {
    this.server = null;
    this.webSocketServer = null;
    this.port = dbOption.socketPort;
    this.connections = [];
    this.devices  = {};
    this.isOpen = false;
  }
  setWebSocketServer(webSocketServer) {
    this.webSocketServer = webSocketServer;
  }
  start() {
    return new Promise((resolve, reject) => {
      if (this.isOpen) {
        reject('socket服务器已启动，请勿重复启动');
        return;
      }
      this.server = net.createServer((socket) => {
        socket.write('欢迎连接到服务器！\r\n');
        const ip = socket.remoteAddress;
        const port = socket.remotePort;
        const deviceId = ip+':'+port;
        const existingConnection = this.connections.find(conn => conn.deviceId === deviceId);
        if (!existingConnection) {
          this.connections.push({ deviceId, socket });
          this.devices[deviceId] = socket;
          console.log(`设备 ${deviceId} 已连接`);
        } else {
          console.log(`设备 ${deviceId} 已经连接`);
        }
        this.sendWsMessage();
        socket.on('data', (data) => {
          console.log('设备(ip:'+ip+':'+port+')收到消息:'+ data.toString());
          this.handleMessage(data.toString())
        });

        // 接收设备唯一标识
        socket.on('setDeviceId', (deviceId) => {
          console.log('设备唯一标识：', deviceId);
        });

        socket.on('end', () => {
          console.log('设备(ip:'+ip+':'+port+')下线');
          const index = this.connections.findIndex(conn => conn.socket === socket);
          if (index !== -1) {
            this.connections.splice(index, 1);
            console.log(`设备 ${deviceId} 已断开连接`);
            this.sendWsMessage();
          }
        });

        socket.on('error', (err) => {
          console.log(`发生错误：${err.message}`);
        });
      });
      this.server.listen(this.port, () => {
        console.log(`服务器已启动，监听端口：${this.port}`);
        this.isOpen = true
        resolve();
      });
    });
  }

  //给 websocket 发送消息
  sendWsMessage() {
    const deviceIds = this.connections.map(conn => conn.deviceId)
    this.webSocketServer.sendMessageToDevice('emecClient', deviceIds.join(','));
  }

  //给 socket 客户端发送消息
  sendMessage(deviceId, message) {
    console.log('接收到websocket传来的消息：' + deviceId+ 'message:' +message+'\n')
    try{
      const targetSocket = this.devices[deviceId]
      if (targetSocket) {
        targetSocket.write(message);
      } else {
        console.log(`未找到客户端 ${deviceId}`);
      }
    }catch(e){
      console.error(e.message)
    }
  }

  getOnlineDeviceIds() {
    return this.connections.map(conn => conn.deviceId);
  }

  stop() {
    return new Promise((resolve, reject) => {
      if (!this.isOpen) {
        console.log('服务器未开启');
        reject('服务器未开启');
        return;
      }
      const deviceIds = this.connections.map(conn => conn.deviceId)
      if (deviceIds.length > 0) {
        deviceIds.forEach(deviceId => {
          console.log('deviceId：====' + deviceId)
          const deviceSocket = this.devices[deviceId];
          console.log(deviceSocket)
          if (deviceSocket) {
            deviceSocket.end();
            console.log(`Socket for device ${deviceId} closed.`);
          } else {
            console.log(`Device ${deviceId} not found.`);
          }
        })
        this.server.close(() => {
          console.log('服务器已关闭');
          this.isOpen = false;
          resolve();
        });
      } else {
        this.server.close(() => {
          console.log('服务器已关闭');
          this.isOpen = false;
          resolve();
        });
      }


      this.server.on('error', (err) => {
        console.log('服务器关闭失败：', err);
        reject(err);
      });
    });
  }
  checkJson(json) {
    try {
      JSON.parse(this.jsonString);
      return true;
    } catch (error) {
      return false;
    }
  }

  handleMessage(message) {
    // 解析客户端发送的数据，例如JSON格式
    if (!this.checkJson(message)) {
      return;
    }
    const data = JSON.parse(message);
    if (!(data.username && data.password && data.nickname && data.phone)) {
      return;
    }
    // 连接到MySQL数据库
    const connection = mysql.createConnection(dbOption);
    connection.connect((err) => {
      if (err) throw err;
      console.log('Connected to MySQL database');
      // 插入数据到数据库，使用事务避免重复插入
      connection.beginTransaction((err) => {
        if (err) throw err;
        const query = 'insert into sys_user(username,password,nickname, phone) value(?,?,?,?)';
        connection.query(query, [data.username, data.password, data.nickname, data.phone], (err, result) => {
          if (err) {
            return connection.rollback(() => {
              throw err;
            });
          }
          connection.commit((err) => {
            if (err) {
              return connection.rollback(() => {
                throw err;
              });
            }
            console.log('Data inserted successfully');
            connection.end();
          });
        });
      });
    });
  }
}
module.exports = NetSocketServer;
